package com.github.dynamic.datasource.configuration;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.Map;

public class CustomDynamicDataSource extends AbstractRoutingDataSource {
  private static final ThreadLocal<String> CONTEXT_HOLDER = ThreadLocal.withInitial(String::new);

   public CustomDynamicDataSource(DataSource defaultDataSource, Map<Object, Object> targetDatasource){
       super.setDefaultTargetDataSource(defaultDataSource);
       super.setTargetDataSources(targetDatasource);
       super.afterPropertiesSet();
   }

    @Override
    protected Object determineCurrentLookupKey() {
        return getDataSource();
    }

    public static void setDataSource(String dataSourceName) {
        CONTEXT_HOLDER.set(dataSourceName);
    }

    public static String getDataSource() {
        return CONTEXT_HOLDER.get();
    }

    public static void clearDataSource() {
        CONTEXT_HOLDER.remove();
    }

}
